import lodash from 'lodash';
import moment from 'moment';
import * as data from './data';
import log from '../../../log';
import * as util from '../../../util';
import * as activityData from '../activity/data';

const likeParms = ''.split(',');
let userColumns = 'id,code,username,avatar,name,nameJp,gender,' +
    'mobile,tel,officePhone,email,regionId,regionName,address,' +
    'ips,createTime,status,birthday,userType,openId,unionid,' +
    'institutionId,idCard';
userColumns = userColumns.split(',');

export function fetch(query, page, pageSize) {
    return util.resolve().then(() => {
        log.info('fetch activityVotes params----', query);
        const pageOpt = {
            page,
            pageSize
        };
        let where = [];
        if (lodash.keys(query).length > 0) {
            lodash.mapKeys(query, (value, key) => {
                if (likeParms.indexOf(key) >= 0) {
                    if (value.length > 0) {
                        where.push([`${key}`, 'like', `%${value}%`]);
                    }
                } else if (value.length > 0) {
                    where.push([`${key}`, '=', `${value}`]);
                }
            });
        }
        if (where.length < 1) {
            where = null;
        }
        return data.fetch(where, 1, pageOpt).then(res => {
            //log.info('fetch activityVotes result----', res.toJSON());
            return util.data(res, 1);
        });
    }).catch(err => {
        log.error('fetch activityVotes is err----', err);
        throw err;
    });
}

export function find(query) {
    return util.resolve().then(() => {
        log.info('find activityVotes params----', query);
        let where = [];
        if (lodash.keys(query).length > 0) {
            lodash.mapKeys(query, (value, key) => {
                if (likeParms.indexOf(key) >= 0) {
                    if (value.length > 0) {
                        where.push([`${key}`, 'like', `%${value}%`]);
                    }
                } else if (value.length > 0) {
                    where.push([`${key}`, '=', `${value}`]);
                }
            });
        }
        if (where.length < 1) {
            where = null;
        }
        return data.find(where, 1).then(res => {
            //log.info('find activityVotes result----', util.data(res));
            return util.data(res);
        });
    }).catch(err => {
        log.error('find activityVotes is err----', err);
        return err;
    });
}

/**
 * 获取排名
 * */
export function top(query) {
    return util.resolve().then(() => {
        log.info('find activityVotes params----', query);
        if (lodash.isEmpty(query.activityId)) {
            throw '参数错误，没有活动id';
        }
        return data.top(query).then(res => {
            //log.info('find activityVotes result----', res);
            res = res[0];
            res = lodash.map(res, i => {
                lodash.forEach(i.keys, (k) => {
                    if (userColumns.indexOf(k) < 0) {
                        i = lodash.omit(i, k);
                    }
                });
                return i;
            });
            return res[0];
        });
    }).catch(err => {
        log.error('find activityVotes is err----', err);
        return err;
    });
}

/**
 * 获取自己的排名
 * */
export function getMyRanking(user, query) {
    return util.resolve().then(() => {
        log.info('find activityVotes params----', query);
        if (lodash.isEmpty(query.activityId)) {
            throw '参数错误，没有活动id';
        }
        //当传递optionId时，为搜索某个业务员的投票数据，不使用当前用户的
        if (query.optionId) {
            user.id = query.optionId;
        }
        return data.myTop(query, user.id).then(res => {
            log.info('find activityVotes result----', res);
            return res[0][0];
        });
    }).catch(err => {
        log.error('find activityVotes is err----', err);
        return err;
    });
}

/**
 * 添加投票
 * */
export function add(user, model) {
    return util.resolve().then(() => {
        log.info('add activityVotes params----', model);
        //判断是否结束
        return activityData.find([{id: model.activityId}], 0).then(res => {
            res = res.toJSON() || [];
            const activity = res[0];
            log.info('activity:', activity);
            if (res.length === 0) {
                throw '活动不存在';
            }

            return data.find({activityId: model.activityId, customerId: user.id}).then(vote => {
                vote = vote || [];
                if (vote.length > 0) {
                    throw '您已经在此活动中投过票了!';
                }
                if (moment(activity.dateEnd) < moment()) {
                    throw '活动已过期，不能投票';
                }
                if (moment(activity.dateStart) > moment()) {
                    throw '活动还未开始，不能投票';
                }
                // 投票信息
                model.id = util.uuid();
                model.createtime = util.now();
                model.customerId = user.id;
                // 客户信息
                const customer = {};
                customer.id = user.id;
                customer.name = model.customerName;
                customer.mobile = model.customermobile;
                delete model.customerName;
                delete model.customermobile;

                return data.add(model, customer).then(res => {
                    //log.info('add activityVotes result----', res);
                    return res;
                });
            });
        });
    }).catch(err => {
        log.error('add activityVotes is err----', err);
        throw err;
    });
}

export function edit(model) {
    return util.resolve().then(() => {
        log.info('edit activityVotes params----', model);

        return data.edit(model).then(res => {
            //log.info('edit activityVotes result----', util.data(res));
            return util.data(res);
        });
    }).catch(err => {
        log.error('edit activityVotes is err----', err);
        throw err;
    });
}

export function del(id) {
    return util.resolve().then(() => {
        log.info('delete activityVotes params----', id);
        return data.del(id).then(res => {
            //log.info('delete activityVotes result----success', util.data(res));
            return util.data(res);
        });
    }).catch(err => {
        log.error('delete activityVotes is err----', err);
        throw err;
    });
}
